package com.ckzp.ext.logs;


import com.ckzp.core.ConfigUtil;
import org.apache.log4j.jdbc.JDBCAppender;
import org.apache.log4j.spi.LoggingEvent;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created by 51594 on 2024/7/7.
 */
public class MyJdbcAppender extends JDBCAppender {

    @Override
    public void append(LoggingEvent event) {
        event.getNDC();
        event.getThreadName();
        event.getMDCCopy();
        Connection conn = null;
        PreparedStatement statement = null;
        try {
            conn = getConnection();
            statement = conn.prepareStatement(getLayout().format(event));
            statement.setString(1, ConfigUtil.getNode());
            statement.setTimestamp(2, new java.sql.Timestamp(event.getTimeStamp()));
            statement.setString(3, event.getLoggerName());
            statement.setString(4, event.getLevel().toString());
            statement.setString(5, event.getRenderedMessage());
            // 获取异常信息
            if (event.getThrowableInformation() != null) {
                statement.setString(6, event.getThrowableInformation().getThrowable().toString());
                statement.setString(7, getResponse(event.getThrowableInformation().getThrowableStrRep()).toString());
            } else {
                statement.setString(6, null);
                statement.setString(7, null);
            }
            statement.executeUpdate();
            statement.close();
        } catch (SQLException e) {
            errorHandler.error("Failed to write to database", e, 0);
        } finally {
            closeConnection(conn);
        }
    }

    /**
     * @param res
     * @return
     */
    private StringBuilder getResponse(String[] res) {
        StringBuilder sb = new StringBuilder();
        if (res == null) return sb;
        for (String s : res) {
            sb.append(s + "\n");
        }
        return sb;
    }

    @Override
    protected Connection getConnection() throws SQLException {
        if (!DriverManager.getDrivers().hasMoreElements()) {
            this.setDriver("sun.jdbc.odbc.JdbcOdbcDriver");
        }
        if (this.connection != null && !connection.isValid(50)) {
            this.connection = null;
        }
        if (this.connection == null) {
            this.connection = DriverManager.getConnection(this.databaseURL, this.databaseUser, this.databasePassword);
        }
        return this.connection;
    }
}
